//
//  UploadSignInPictureView.m
//  优学荟管理系统
//
//  Created by 星道 on 17/8/21.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "UploadSignInPictureView.h"
#import "AppDelegate.h"

@implementation UploadSignInPictureView
{
    /** 黑色的背景 */
    IBOutlet UIView *_blackView;
    /** 内容View */
    IBOutlet UIView *_contentView;
    /** 那俩个图片上传的按钮在这里 */
    IBOutletCollection(UIButton) NSArray *_imgArr;

    void (^_Complete)();
    /** 选择图片的回调 */
    void (^_SelectImg)(UIImage *img);

    /** 用户ID */
    NSString *_uids;
    /** 报名或订单ID */
    NSString *_enrollInfoIds;
    /** 课程ID */
    NSString *_lessonId;

    NSMutableDictionary *_imgDict;
}


#pragma mark - 实例化
+ (instancetype)UploadSignInPictureView_ConfigViewWithLessonId:(NSString *)lessonId Uids:(NSString *)Uids enrollInfoIds:(NSString *)enrollInfoIds Complete:(void (^)())Complete
{
    return [[self alloc] init_ConfigViewWithLessonId:lessonId Uids:Uids enrollInfoIds:enrollInfoIds Complete:Complete];
}

- (instancetype)init_ConfigViewWithLessonId:(NSString *)lessonId Uids:(NSString *)Uids enrollInfoIds:(NSString *)enrollInfoIds  Complete:(void (^)())Complete
{
    self = [[[NSBundle mainBundle] loadNibNamed:[UploadSignInPictureView description] owner:nil options:nil] firstObject];
    if (self)
    {
        _uids = Uids;
        _enrollInfoIds = enrollInfoIds;
        _lessonId = lessonId;
        _Complete = Complete;
        _imgDict = [NSMutableDictionary dictionary];

        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT);

        // 显示
        [self Show];
    }
    return self;
}

#pragma mark - 单击事件
/** 关闭 */
- (IBAction)Cancle:(UIButton *)sender
{
    [self Close];
}

/** 提交 */
- (IBAction)Sure:(UIButton *)sender
{
//    _imgDict.allKeys.count <= 0 ? [HUD showError:@"请至少选择一张图片上传"]:[self RefreshData];
    [self RefreshData];
}

/** 上传图片及数据 */
- (void)RefreshData
{
    __block MBProgressHUD *hud = [self HUD];
    NSDictionary *params = @{
                             @"action":@"saveRecord",
                             @"uids":_uids,
                             @"enrollInfoIds":_enrollInfoIds,
                             @"lessonId":_lessonId
                             };
    [NetManager UpdataImgsWithURL:LLBaseURL(@"yxhUser.do") imgs:[_imgDict.allValues copy] parameter:params Progress:^(NSProgress * _Nonnull uploadProgress) {

        if (uploadProgress.totalUnitCount == uploadProgress.completedUnitCount)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud setHidden:YES];
                [HUD showHUD];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                hud.label.text = [NSString stringWithFormat:@"总大小：%.2fM,当前大小:%.2fM",uploadProgress.totalUnitCount/1024.0/1024.0,uploadProgress.completedUnitCount/1024.0/1024.0];
            });
        }

    }success:^(id obj) {
        
        [hud setHidden:YES];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingMutableLeaves error:nil];
        if ([dict[@"code"] isEqualToNumber:@1000])
        {
            [HUD showSuccess:@"签到成功"];
            if (_Complete)
            {
                _Complete ();
            }
            [self performSelector:@selector(Close) withObject:nil afterDelay:2];
        }
        else
        {
            [HUD showError:dict[@"msg"]];
        }


    } fail:^(NSError *error) {
        [hud setHidden:YES];
        [HUD showError:NetErr];
    }];
}

/** 图片 1100第一张图片 1101第二张图片 */
- (IBAction)SelectImg:(UIButton *)sender
{
    // 根据按钮状态判断是删除图片还是增加图片
    sender.selected ? [self DeleteImg:sender]:[self AlertController:^(UIImage *img) {
        // 图片下来了
        [sender setBackgroundImage:img forState:(UIControlStateSelected)];
        sender.selected = !sender.selected;
        [_imgDict setObject:img forKey:@(sender.tag)];
    }];

}
#pragma mark - 实现
// 显示
- (void)Show
{
    [[[AppDelegate shareAppDelegate] getCurrentUIVC].view addSubview:self];
    
//    [[UIApplication sharedApplication].keyWindow addSubview:self];
    _blackView.alpha = 0;
    _contentView.alpha = 0;
    _contentView.transform = CGAffineTransformMakeScale(-2, -2);

    [UIView animateWithDuration:0.3 animations:^{
        _blackView.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            _contentView.transform = CGAffineTransformIdentity;
            _contentView.alpha = 1;
        }];
    }];
}

// 关闭
- (void)Close
{
    [UIView animateWithDuration:0.3 animations:^{
        _contentView.transform = CGAffineTransformMakeScale(-2, -2);
        _contentView.alpha = 0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            _blackView.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
}


/** AlertController 增加图片*/
- (void)AlertController:(void (^)(UIImage *img))Complete
{
    _SelectImg = Complete;
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self ConfigImagePickController:YES];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self ConfigImagePickController:NO];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    
   [[[AppDelegate shareAppDelegate] getCurrentUIVC] presentViewController:AlertController animated:YES completion:nil];
}

/** 删除按钮上的图片 */
- (void)DeleteImg:(UIButton *)Button
{
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除已上传的图片?" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        Button.selected = !Button.selected;
        [_imgDict removeObjectForKey:@(Button.tag)];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:AlertController animated:YES completion:nil];
}

/** 初始相机与相册 ,根据isCamera调用相机或相册*/
- (void)ConfigImagePickController:(BOOL)isCamera
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = isCamera ? UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.navigationBar.barTintColor = [UIColor blackColor];
    [[[AppDelegate shareAppDelegate] getCurrentUIVC] presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        if (_SelectImg)
        {
            _SelectImg (img);
        }
    }];
}

- (MBProgressHUD *)HUD
{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    HUD.mode = MBProgressHUDModeText;
    HUD.removeFromSuperViewOnHide = YES;
    HUD.backgroundColor = ColorRGBA(0, 0, 0, 0.5);
    HUD.bezelView.color =[UIColor blackColor];
    HUD.contentColor = [UIColor whiteColor];
    HUD.label.text = @"正在上传中...0%";
    return HUD;
}
 
@end
